<template>
  <div>
    <div style="width: 100%; height: 40px; position: absolute; top: 100px; padding-top: 10px; ">
      <Alert type="warning" style="width: 550px; float: left;" show-icon>
        您正在修改『{{ $route.query.name }}』的权限，请谨慎操作，勾选下方表格内对应权限并保存。
      </Alert>
      <vxe-button icon="iconfont icon-baocun" status="warning" content="保存权限" style="float: right; margin-right: 270px;"
                  @click="saveRights"></vxe-button>
      <vxe-button type="text" status="danger" href="javascript:void(0);"
                  style="float: right; margin-right: 10px; line-height: 30px;" @click="seniorSetting = !seniorSetting">
        高级设置
      </vxe-button>
    </div>
    <div style="margin-top: 40px; clear: both; width: 100%;height: 1px;"></div>
    <div v-if="seniorSetting" style="margin-top: 10px;">
      <vxe-button content="选择所有「读」权限" @click="quickCheck('read')"></vxe-button>
      <vxe-button content="选择所有「写」权限" @click="quickCheck('write')"></vxe-button>
      <vxe-button content="只选择所有「读」权限" @click="quickCheck('only_read')"></vxe-button>
      <vxe-button content="只选择所有「写」权限" @click="quickCheck('only_write')"></vxe-button>
      <vxe-button content="选择所有权限" @click="quickCheck('all')"></vxe-button>
      <vxe-button status="danger" content="取消所有权限" @click="quickCheck('cancel_all')"></vxe-button>
    </div>
    <Tabs :animated="false" @on-click="tabsChange">
      <Tab-pane label="全部">
        <auth-table
          v-if="currentModule === 'all'"
          :checked-rights="checkedRights"
          :indeterminate-rights="indeterminateRights"
          :merge-cells="mergeCells"
          :table-data="tableData"
          :component-key="componentKey"
          @checkboxChange="checkboxChange"
        ></auth-table>
      </Tab-pane>

      <Tab-pane v-for="(item,key) in moduleRights" :key="key" :label="item.name">
        <div style="width: 100%">
          <auth-table
            v-if="currentModule === item.key"
            :checked-rights="checkedRights"
            :indeterminate-rights="indeterminateRights"
            :merge-cells="mergeCells"
            :table-data="tableData"
            :component-key="componentKey"
            @checkboxChange="checkboxChange"
          ></auth-table>
        </div>
      </Tab-pane>
    </Tabs>
  </div>
</template>

<script>
import { roleRightsUpdate, roleRights } from '@/api/role'
import AuthTable from './components/table'

export default {
  name: 'manager_auth',
  components: {
    AuthTable
  },
  data () {
    return {
      seniorSetting: false,
      componentKey: 0,
      mergeFooterItems: [],
      mergeCells: [],
      tableData: [],
      checkedRights: [],
      indeterminateRights: [],
      moduleRights: [],
      currentModule: 'all',
      rightsList: [],
      requestData: {}
    }
  },
  mounted () {
    this.loadData()
  },
  methods: {
    saveRights () {
      this.$XModal.alert({
        message: '添加中，请稍后',
        status: 'loading',
        id: 'loading'
      })
      let checkedRights = []
      for (let key in this.checkedRights) {
        if (this.checkedRights[key]) {
          checkedRights.push(key)
        }
      }
      let indeterminateRights = []
      for (let key in this.indeterminateRights) {
        if (this.indeterminateRights[key]) {
          indeterminateRights.push(key)
        }
      }
      let rights = checkedRights.concat(indeterminateRights)
      roleRightsUpdate({
        role: this.$route.params.role,
        rights: rights.join(',')
      }).then(({ data, status }) => {
        if (status === 200) {
          // 添加成功
          this.$XModal.close('loading')
          this.$XModal.alert({
            message: data.message,
            status: 'success'
          })
          this.formData2 = Object.assign({}, formData)
        } else {
          this.$XModal.close('loading')
          this.$XModal.alert({
            message: data.message,
            status: 'error'
          })
        }
      }).catch((error) => {
        this.$XModal.close('loading')
        this.$XModal.alert({
          message: error.response.data.message,
          status: 'error'
        })
      })
    },
    quickCheck (type) {
      if (type === 'cancel_all') {
        this.checkedRights = []
        this.indeterminateRights = []
        return
      }
      for (let key in this.tableData) {
        for (let key2 in this.tableData[key].functionRights) {
          if (type.indexOf('only_') === 0) {
            this.checkedRights = []
            this.indeterminateRights = []
            type = type.slice(5)
            if (this.tableData[key].functionRights[key2].type === type || type === 'all') {
              // 选择
              this.checkedRights[this.tableData[key].functionRights[key2].key] = true
              this.checkedNodeChange(true, this.tableData[key].functionRights[key2])
            }
          } else {
            if (this.tableData[key].functionRights[key2].type === type || type === 'all') {
              // 选择
              this.checkedRights[this.tableData[key].functionRights[key2].key] = true
              this.checkedNodeChange(true, this.tableData[key].functionRights[key2])
            }
          }
        }
      }
      this.componentKey++
    },
    tabsChange (event) {
      if (event === 0) {
        this.tableData = this.requestData.rightsList
        this.mergeCells = this.requestData.mergeCells
        this.currentModule = 'all'
        return
      }
      this.currentModule = this.moduleRights[event - 1].key
      this.tableData = []
      let rowspan = 0
      for (let key in this.requestData.rightsList) {
        if (this.requestData.rightsList[key].pid === this.moduleRights[event - 1].id) {
          // 移除
          this.tableData.push(this.requestData.rightsList[key])
          rowspan++
        }
      }
      this.mergeCells = [{ col: 0, colspan: 1, row: 0, rowspan: rowspan }]
    },
    loadData () {
      roleRights({
        role: this.$route.params.role
      }).then(({ data, status }) => {
        this.requestData = data.data
        this.tableData = this.requestData.rightsList
        this.mergeCells = this.requestData.mergeCells
        this.moduleRights = this.requestData.moduleRights

        for (let key in this.tableData) {
          for (let key2 in this.tableData[key].functionRights) {
            let rights = this.tableData[key].functionRights[key2]
            if (this.requestData.rights.indexOf(rights.key) !== -1) {
              this.checkedRights[rights.key] = true
              this.checkedNodeChange(true, rights)
            }
          }
        }
        this.componentKey++
      })
    },
    checkboxChange ({ event, rights }) {
      if (rights.pid === 0 || rights.parentRights.pid === 0) {
        this.indeterminateRights[rights.key] = event.checked
      } else {
        this.indeterminateRights[rights.key] = false
      }

      // 选择最顶级的权限
      if (rights.pid === 0) {
        for (let key in this.tableData) {
          if (this.tableData[key].pid === rights.id) {
            this.checkedRights[this.tableData[key].key] = event.checked
            this.indeterminateRights[this.tableData[key].key] = event.checked

            for (let key2 in this.tableData[key].functionRights) {
              this.checkedRights[this.tableData[key].functionRights[key2].key] = event.checked
            }
          }
        }
        this.componentKey++
        return true
      }
      // 修改下级
      if (rights.functionRights) {
        // 如果有下级，修改所有下级
        for (let key in rights.functionRights) {
          // 选择所有下级
          this.checkedRights[rights.functionRights[key].key] = event.checked
        }
      }

      // 修改上级（通过递归）
      // 查看当前等级下的是否全部选中，如果全部选中的话，就选中上级的
      this.checkedNodeChange(event.checked, rights)
      this.componentKey++
    },
    checkedNodeChange (checked, rights) {
      if (rights.parentRights.pid === 0) {
        // 第二级，判断第二级是否全部选中
        let result = true
        for (let key in this.tableData) {
          if (this.tableData[key].pid === rights.parentRights.id && !this.checkedRights[this.tableData[key].key]) {
            result = false
          }
        }
        this.checkedRights[rights.parentRights.key] = result
        if (!result) {
          let indeterminateStatus = false
          for (let key in this.tableData) {
            if (this.tableData[key].pid === rights.parentRights.id) {
              if (this.indeterminateRights[this.tableData[key].key] || this.checkedRights[this.tableData[key].key]) {
                indeterminateStatus = true
              }
            }
          }
          this.indeterminateRights[rights.parentRights.key] = indeterminateStatus
        }
        return
      }

      // 第三级
      for (let key in this.tableData) {
        if (this.tableData[key].key === rights.parentRights) {
          let result = true
          let indeterminateStatus = false
          for (let key2 in this.tableData[key].functionRights) {
            if (!this.checkedRights[this.tableData[key].functionRights[key2].key]) {
              result = false
            } else {
              indeterminateStatus = true
            }
          }
          this.checkedRights[rights.parentRights] = result
          this.indeterminateRights[rights.parentRights] = indeterminateStatus
          this.checkedNodeChange(checked, this.tableData[key])
          return
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
